const config = require('./config')
const login=require('./login')
const common=require('./common')
const baseRequest = require('./baseRequest')
const takePicture = async(options) => {
  const takeOptions = { ...options, ...options?.currentTarget?.dataset }
  console.log("takePicture", takeOptions)
  const itemList = []
  if (takeOptions.camera) {
    itemList.push("拍照")
  }
  if (takeOptions.album) {
    itemList.push("从手机相册选择")
  }
  if (takeOptions.message) {
    itemList.push("从聊天记录选择")
  }
  if(itemList.length<=0){
    console.log("直接选择相册和相机")
    return new Promise((resolve, reject) => {
      wx.chooseImage({
        count: 1, //默认9
        sizeType: ['original', 'compressed'], //可以指定是原图还是压缩图，默认二者都有
        sourceType: ["album", "camera"] //从相册选择
      }).then(res => { resolve(res.tempFilePaths[0]) }, res => { reject("取消选择") })
    });
  }
  return wx.showActionSheet({
    itemList
  }).then((res) => {
    switch (itemList[res.tapIndex]) {
      case '拍照':
        return new Promise((resolve, reject) => {
          wx.chooseImage({
            count: 1, //默认9
            sizeType: ['original', 'compressed'], //可以指定是原图还是压缩图，默认二者都有
            sourceType: ["camera"] //从相册选择
          }).then(res => { resolve(res.tempFilePaths[0]) }, res => { reject("取消选择") })
        })
        break;
      case '从手机相册选择':
        return new Promise((resolve, reject) => {
          wx.chooseImage({
            count: 1, //默认9
            sizeType: ['original', 'compressed'], //可以指定是原图还是压缩图，默认二者都有
            sourceType: ["album"] //从相册选择
          }).then(res => { resolve(res.tempFilePaths[0]) }, res => { reject("取消选择") })
        });
        break;
      case '从聊天记录选择':
        return new Promise((resolve, reject) => {
          if (wx.chooseMessageFile) {
            return wx.chooseMessageFile({
              count: 1,
              type: 'image'
            }).then(res => { resolve(res.tempFiles[0].path) }, res => { reject("取消选择") })
          } else {
            wx.showModal({
              title: '提示',
              content: '当前微信版本过低，无法使用该功能，请升级到最新微信版本后重试。'
            })
            reject(undefined)
          }
        }).then(res => {
          return res
        })
        break;
      default:
    }
  },
  res=>{return new Promise((resolve, reject) => {reject(undefined) })}
  )
}
module.exports = {
  /**
   * 
   * @param {string} filePath 
   * @param {Array} data 
   * @returns {Promise<string>}
   */
  checkImage:async(filePath,data)=>{
      return new Promise((resolve,reject)=>{
        login.getJwtPayload().then(jwt=>{
          
          const split=jwt.split(".")
          const arrayBuffer =wx.base64ToArrayBuffer(split[1])
          const json=String.fromCharCode.apply(null,new Uint8Array(arrayBuffer))
          const {openId}=JSON.parse(json);
          console.log(openId)
          const headers={}
          headers.authorization='Bearer '+jwt
          const uploadTask = wx.uploadFile({
            filePath: filePath,
            name: 'upload',
            url: config.baseUrl + 'wxv2' + "/" + 'check/'+config.appId+"/"+openId,
            formData: { appId: config.appId, ...data },
            header:headers,
            success: async (res) => {
          //     // wx.hideLoading()
              const ret = await baseRequest.requestHandle(JSON.parse(res.data))
              resolve(ret.safe)
            },
            fail:(res)=>{
              console.error("请检查网络",res)
              reject(common.error("请检查网络",-1))
            },
            complete:(res)=>{
              wx.hideLoading({})
            }
          });

          if(uploadTask && uploadTask.onProgressUpdate){
            uploadTask.onProgressUpdate(res => {
              wx.showLoading({
                title: '处理中',
              })
            })
          }


        },
        err=>{
          reject(err)
        })
      })
  },
  uploadFile: async (filePath, data) => {
    return new Promise((resolve, reject) => {
      login.getJwtPayload().then(
        success=>{
          const split=success.split(".")
          const arrayBuffer =wx.base64ToArrayBuffer(split[1])
          const json=String.fromCharCode.apply(null,new Uint8Array(arrayBuffer))
          const {openId}=JSON.parse(json);

          const headers={}
          headers.authorization='Bearer '+success
          const uploadTask = wx.uploadFile({
            filePath: filePath,
            name: 'upload',
            url: config.baseUrl + 'wxv2' + "/" + 'upload/'+config.appId+"/"+openId,
            formData: { appId: config.appId, ...data },
            header:headers,
            success: async (res) => {
              // wx.hideLoading()
              const ret = await baseRequest.requestHandle(JSON.parse(res.data))
              resolve({ url: ret.url, id: ret.id })
            },
            fail:(res)=>{
              console.error("请检查网络",res)
              reject(common.error("请检查网络",-1))
            },
            complete:(res)=>{
              wx.hideLoading({
              })
            }
          });
          if(uploadTask && uploadTask.onProgressUpdate){
            uploadTask.onProgressUpdate(res => {
              wx.showLoading({
                title: '上传进度' + res.progress + "%",
              })
            })
          }
        },
        err=>{
          reject(err)
        }
      )
    })
  },
  takePicture
}